package me.leiusual.sharing.ui

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.os.Vibrator
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import cn.bingoogolapple.photopicker.activity.BGAPhotoPickerActivity
import cn.bingoogolapple.qrcode.core.QRCodeView
import kotlinx.android.synthetic.main.activity_scan.*
import timber.log.Timber


/**
 * author: leiusual
 * create on: 2019-08-07
 * description:
 */
class ScanActivity : AppCompatActivity(), QRCodeView.Delegate {

  companion object {
    private const val REQUEST_CODE_CHOOSE_QRCODE_FROM_GALLERY = 666

    private const val RESULT_DATA = "result_data"

    fun intent(context: Context): Intent {
      return Intent(context, ScanActivity::class.java)
    }

    fun getResult(data: Intent?): String? {
      return data?.getStringExtra(RESULT_DATA)
    }
  }

  override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(me.leiusual.sharing.R.layout.activity_scan)
    zxing_view.setDelegate(this)

    toolbar.setNavigationOnClickListener {
      finish()
    }

    toolbar.setOnMenuItemClickListener {

      // 从相册选取二维码图片
      val photoPickerIntent = BGAPhotoPickerActivity.IntentBuilder(this)
          .cameraFileDir(null)
          .maxChooseCount(1)
          .selectedPhotos(null)
          .pauseOnScroll(false)
          .build()
      startActivityForResult(photoPickerIntent, REQUEST_CODE_CHOOSE_QRCODE_FROM_GALLERY)
      true
    }
  }

  override fun onStart() {
    super.onStart()
    zxing_view.startCamera()
    zxing_view.startSpotAndShowRect()
  }

  override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
    super.onActivityResult(requestCode, resultCode, data)

    zxing_view.startSpotAndShowRect()

    if (resultCode == Activity.RESULT_OK && requestCode == REQUEST_CODE_CHOOSE_QRCODE_FROM_GALLERY) {
      val picturePath = BGAPhotoPickerActivity.getSelectedPhotos(data)[0]
      zxing_view.decodeQRCode(picturePath)
    }
  }

  override fun onStop() {
    zxing_view.stopCamera()
    super.onStop()
  }

  override fun onDestroy() {
    zxing_view.onDestroy()
    super.onDestroy()
  }

  override fun onScanQRCodeSuccess(result: String?) {
    Timber.v("onScanQRCodeSuccess result = %s", result)

    vibrate()

    if (result.isNullOrBlank()) {
      Toast.makeText(this, "未发现二维码", Toast.LENGTH_SHORT).show()
      return
    }

    setResult(Activity.RESULT_OK, Intent().putExtra(RESULT_DATA, result))
    finish()
  }

  override fun onCameraAmbientBrightnessChanged(isDark: Boolean) {
    Timber.v("onCameraAmbientBrightnessChanged isDark = %s", isDark)
  }

  override fun onScanQRCodeOpenCameraError() {
    Timber.v("onScanQRCodeOpenCameraError")
  }

  @Suppress("DEPRECATION")
  private fun vibrate() {
    val vibrator = getSystemService(Context.VIBRATOR_SERVICE) as Vibrator
    vibrator.vibrate(200)
  }
}